package com.bright.hxj.qchz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bright.ghj.common.util.DateUtil;
import com.bright.hxj.qchz.mapper.DuijieBaowenLogMapper;
import com.bright.hxj.qchz.pojo.bo.DuijieReturnMsg;
import com.bright.hxj.qchz.pojo.po.DuijieBaowenLog;
import com.bright.hxj.qchz.pojo.po.TaskAsync;
import com.bright.hxj.qchz.service.TaskAsyncService;
import com.bright.hxj.qchz.service.TaskManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.function.Function;

/**
 * @Author hxj
 * @Date 2025/1/4 17:03
 * @Description
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class TaskManagerImpl implements TaskManager {

    private final TaskAsyncService taskAsyncService;
    private final DuijieBaowenLogMapper duijieBaowenLogMapper;


    @Override
    public void writeToLogTable(JSONObject jsonObject, String userName, String methodName, String taskId, String ztId) {
//        String sql = "insert into duijie_baowen_log(userName, methodName, taskId, ztId, baowen, createDate) values(?,?,?,?,?,?)";
//        duijie_shi_jdbcTemplate.update(sql, new Object[]{userName, methodName, taskId, ztId, jsonObject.toString(), new Date()});
        DuijieBaowenLog duijieBaowenLog = new DuijieBaowenLog(null, userName, methodName, taskId, ztId, jsonObject.toString(), null, null);
        duijieBaowenLogMapper.insert(duijieBaowenLog);
    }

    @Override
    public boolean insertTaskToDB(TaskAsync taskAsync) {

//        try {


//            duijie_shi_jdbcTemplate.update("insert into taskAsync(taskId, userName, methodName, years, ztId, runFlag, status, creator, createDate) " +
//                    "values(?,?,?,?,?,?,?,?,?)", new Object[]{taskId, userName, methodName, years, ztId, true, ASYNC_TASK_WAITING, userName, DateUtil.getCurrDate()});
           return taskAsyncService.save(taskAsync);

//        } catch (Exception e) {
//            log.error("创建任务时出错 ", e);
//            return new DuijieReturnMsg("创建任务时出错：" + e.getMessage());
//        }
//        return new DuijieReturnMsg(true, null);
    }

    @Override
    public void updateTaskStatus(String taskId, String userName, int statusFlag, String msg, Object data) {
        // taskAsync表的content字段是给第三方看的 data字段是给我们自己维护人员看的

//        Date beginDate;
        double duration;
        try {
            // 计算耗时
            List<TaskAsync> lists = getTaskDataByTaskId(taskId);
            if (lists.size() > 0) {
                TaskAsync taskAsync = lists.get(0);
                Date createDate = taskAsync.getCreateDate();
//                beginDate = DateUtil.parseStringFormat(createDateObj.toString(), "yyyy-MM-dd hh:mm:ss");
                Date nowDate = new Date();
                duration = (nowDate.getTime() - createDate.getTime())/1000F;
                taskAsync.setDuration(duration);

                taskAsync.setData(data == null ? "" : data.toString());

    //            duijie_shi_jdbcTemplate.update("update taskAsync set status=?, okFlag=?, content=?, data=?, writer=?, writeDate=?, duration=? where taskId=?",
    //                    new Object[]{statusFlag, statusFlag == ASYNC_TASK_SUCCESS, msg, dataStr, userName, DateUtil.getCurrDate(), duration, taskId});
                taskAsync.setStatus(statusFlag);
                taskAsync.setOkFlag(statusFlag == ASYNC_TASK_SUCCESS);
                taskAsync.setContent(msg);
                taskAsync.setWriter(userName);
                taskAsync.setWriteDate(new Date());
                taskAsyncService.save(taskAsync);

            }
        } catch (Exception e) {
            throw new RuntimeException("更新任务状态时出错：", e);
        }

//        return null;
    }

    @Override
    public List<TaskAsync> getTaskDataByTaskId(String taskId) {
        return getTaskDataByTaskId(taskId, Function.identity());
    }

    @Override
    public List<TaskAsync> getTaskDataByTaskId(String taskId, Function<LambdaQueryWrapper<TaskAsync>, LambdaQueryWrapper<TaskAsync>> queryWrapperFunction) {

//        return duijie_shi_jdbcTemplate.queryForListList("select " + columnSql + " from taskAsync where taskId=? " + subSql, new Object[]{taskId});
        LambdaQueryWrapper<TaskAsync> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskAsync::getTaskId, taskId);
        queryWrapper = queryWrapperFunction.apply(queryWrapper);
        return taskAsyncService.list(queryWrapper);
    }


    @Override
    public DuijieReturnMsg getTaskStatus(String taskId) {
//        List<List<Object>> lists = duijie_shi_jdbcTemplate.queryForListList("select methodName, status, content from taskAsync where taskId=? and runFlag=1",
//                new Object[] {taskId});
        List<TaskAsync> lists = getTaskDataByTaskId(taskId, wrapper -> wrapper.eq(TaskAsync::getRunFlag, true));
        if (lists.size() == 0) {
            return new DuijieReturnMsg("不存在该任务号！");
        }
        TaskAsync taskAsync = lists.get(0);

        int status = taskAsync.getStatus();
        String errorMessage; // 错误信息 成功时为null
        if (status == ASYNC_TASK_CHECK_FAILED || status == ASYNC_TASK_ERROR) {
            // 数据校验失败的情况
            errorMessage = taskAsync.getContent();
        } else {
            // 成功的情况
            errorMessage = null;
        }

        JSONObject result = new JSONObject();
        result.put("RWID", taskId);
        result.put("RWLX", taskAsync.getMethodName());
        result.put("RWZT", status);
        result.put("CWXX", errorMessage);

        return new DuijieReturnMsg(true, result);
    }

}
